import React, { Component } from 'react';
import style from './index.module.scss'

class index extends Component {
    constructor(props) {
        super(props);
        this.state = {
            countdown: this.getCountdown(),

        };
    }

    // 定时器，每秒获取一次时间
    componentDidMount() {
        this.interval = setInterval(() => {
            this.setState({
                countdown: this.getCountdown(),
            });

        }, 1000);
    }
    // 组件销毁清除定时器
    componentWillUnmount() {
        clearInterval(this.interval);
    }

    // 每小时开始倒计时，以偶数整点为开始
    getCountdown() {
        const now = new Date();
        // 开始时间，当前整点时间余2为判断，求当前最近欧偶数点
        const startHour = now.getHours() % 2 === 0 ? now.getHours() : now.getHours() - 1;

        const startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), startHour, 0, 0);
        // console.log(startTime);
        // 倒计时结束时间，开始时间加2小时
        const endTime = new Date(startTime.getTime() + 2 * 60 * 60 * 1000);
        // 返回剩余倒计时的时间
        return Math.floor((endTime - now) / 1000);

    }
    // 返回倒计时的时分秒
    formatTime(time) {
        const hours = Math.floor(time / 3600).toString().padStart(2, '0');
        const minutes = Math.floor((time % 3600) / 60).toString().padStart(2, '0');
        const seconds = (time % 60).toString().padStart(2, '0');
        return (
            <p>
                <span className={style.timeBox}>{hours}</span>:
                <span className={style.timeBox}>{minutes}</span>:
                <span className={style.timeBox}>{seconds}</span>
            </p>
        )
    }

    render() {
        return (
            <div className={style.skillBox}>
                <span className={style.SkillText}>整点秒杀</span>
                {this.formatTime(this.state.countdown)}
                <span className={style.SkillText2}>后结束</span>
            </div>
        );
    }
}

export default index;